import time
import sys
import json
import io
import traceback

# 设置sys.stdout的编码为UTF-8
sys.stdout.reconfigure(encoding='utf-8')
# 创建一个新的输出流，并设置编码为UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# 将 当且路径 添加到path中
sys.path.append(r'.')
from DrissionPage import ChromiumPage
from DrissionPage._pages.chromium_tab import ChromiumTab


def load_param_datas_from_file(file_path):
    with open(file_path, "r", encoding='utf-8') as f:
        json_file_datas = json.load(f)  # load的传入参数为字符串类型
        return json_file_datas


def item_upload_taobao():
    json_data = load_param_datas_from_file('tmall_upload_item.data.json')
    port = json_data['port']
    uploadUrl = json_data['uploadUrl']

    itemDataBean = json_data['itemDataBean']
    frameSearchImageBeans = json_data['frameSearchImageBeans']

    page = ChromiumPage(addr_or_opts='127.0.0.1:' + str(port))
    tab = page.new_tab()  # 新建标签页，获取标签页对象
    tab.get(uploadUrl)
    # 等待页面加载
    tab.wait.load_start()

    from tmall import tmall_click_and_input_util
    from tmall import tmall_iframe_search_image_util

    try:
        # 搜索图片
        tmall_iframe_search_image_util.frame_search_images(tab, frameSearchImageBeans)
    except:
        traceback.print_exc()

    try:
        # 颜色
        colorBeans = json_data['colorBeans']
        tmall_click_and_input_util.color_chima_beans(tab, colorBeans)
    except:
        traceback.print_exc()

    try:
        chimaBeans = json_data['chimaBeans']
        tmall_click_and_input_util.color_chima_beans(tab, chimaBeans)
    except:
        traceback.print_exc()

    try:
        # 点击事件或输入框
        paramBeans = json_data['paramBeans']
        tmall_click_and_input_util.page_click_input(tab, paramBeans)
    except:
        traceback.print_exc()

    # tab.close()


item_upload_taobao()
